package com.eric.service.impl;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eric.domain.bso.ChildType;
import com.eric.domain.bso.TypeTree;
import com.eric.domain.dto.EquipTypeDto;
import com.eric.domain.dto.MaterialTypeDto;
import com.eric.domain.po.EquipType;
import com.eric.domain.po.Equipment;
import com.eric.mapper.EquipTypeMapper;
import com.eric.service.IEquipTypeService;
import com.eric.service.ILocationService;
import com.eric.utils.PublicTools;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import static com.eric.utils.Constant.PAGE_CURRENT;
import static com.eric.utils.Constant.PAGE_SIZE;

/**
 * <p>
 * 设备类型 服务实现类
 * </p>
 *
 * @author 新哥
 * @since 2024-04-26
 */
@Service
@Transactional
@RequiredArgsConstructor
public class EquipTypeServiceImpl extends MPJBaseServiceImpl<EquipTypeMapper, EquipType> implements IEquipTypeService {
    private final ILocationService locationService;
    @Override
    @Transactional
    public SaResult saveOneEqTypeService(EquipTypeDto equipTypeDto) {

        if (BeanUtil.isEmpty(equipTypeDto)) {
            return SaResult.error("对象不能为空");
        }

        EquipTypeDto equipTypeDtoChecked = checkedObjStr(equipTypeDto);

        if (StrUtil.isBlank(equipTypeDtoChecked.getParentType())) {
            return SaResult.error("一级分类名称不能为空");
        }
        if (StrUtil.isBlank(equipTypeDtoChecked.getChildType())){
            return SaResult.error("二级分类名称不能为空");
        }

        MPJLambdaWrapper<EquipType>wrapper = new MPJLambdaWrapper<EquipType>()
                .eq("parent_type", equipTypeDtoChecked.getParentType())
                .eq("child_type", equipTypeDtoChecked.getChildType());
        EquipType equipType = getOne(wrapper);
        if (!BeanUtil.isEmpty(equipType)) {
            return SaResult.error("已存在数据");
        }

        String parentType = equipTypeDtoChecked.getParentType();
        String childType = equipTypeDtoChecked.getChildType();
        String fullName=parentType+":"+childType;
        equipTypeDtoChecked.setFullName(fullName);
        save(BeanUtil.copyProperties(equipTypeDtoChecked, EquipType.class));
        return SaResult.ok();
    }

    @Override
    public SaResult modifyOneService(EquipTypeDto equipTypeDto) {
        if (BeanUtil.isEmpty(equipTypeDto)) {
            return SaResult.error("对象不能为空");
        }
        EquipTypeDto equipTypeDtoChecked = checkedObjStr(equipTypeDto);
//       获取到需要修改的数据行的id
        Integer id = equipTypeDtoChecked.getId();
//        根据id查询数据库中完整的数据---dto数据有些字段可能是null）
        EquipType equipType = query().eq("id", id).one();

        String parentType;
        String childType;

        if (equipTypeDtoChecked.getParentType() == null&&equipTypeDtoChecked.getChildType()==null) {
            String typeParentType = equipType.getParentType();
            String typeChildType = equipType.getChildType();
            String fullName=typeParentType+":"+typeChildType;
            equipTypeDtoChecked.setFullName(fullName);
            updateById(BeanUtil.copyProperties(equipTypeDtoChecked, EquipType.class));
            return SaResult.ok();
        }

//        判断equipTypeDtoChecked中两个字段，parentType,childType
        if (equipTypeDtoChecked.getParentType()==null){
            parentType=equipType.getParentType();
        }
        else {
            parentType=equipTypeDtoChecked.getParentType();
        }

        if (equipTypeDtoChecked.getChildType()==null){
            childType=equipType.getChildType();
        }
        else {
            childType=equipTypeDtoChecked.getChildType();
        }

//        通过自定义的typeDto中字段，查询数据库中有没有存在相同的对象
        MPJLambdaWrapper<EquipType>wrapper=new MPJLambdaWrapper<EquipType>()
                .eq("parent_type",parentType)
                .eq("child_type", childType);
        EquipType one = getOne(wrapper);

        if (!BeanUtil.isEmpty(one)) {
            equipTypeDtoChecked.setParentType(null);
            equipTypeDtoChecked.setChildType(null);
            equipTypeDtoChecked.setFullName(null);
            updateById(BeanUtil.copyProperties(equipTypeDtoChecked, EquipType.class));
            return SaResult.ok("succeed!");
        }

        String fullName=parentType+":"+childType;
        equipTypeDtoChecked.setFullName(fullName);
        updateById(BeanUtil.copyProperties(equipTypeDtoChecked, EquipType.class));
        return SaResult.ok("succeed!");
    }


    @Override
    public SaResult getAllService(Integer current,Integer pageSize) {
        if (current==null){
            current= PAGE_CURRENT;
        }
        if (pageSize==null){
            pageSize=PAGE_SIZE;
        }
        Page<EquipType> page=new Page<>(current,pageSize);
        List<EquipType> equipTypeList =query()
                .page(page).getRecords();

        List<TypeTree> equipTypeTree = getEquipTypeTree(equipTypeList);

        return SaResult.data(equipTypeTree);
    }






    @Override
    public SaResult getAllCountService() {
        String locationAddress = locationService.getAllByLoginId();
        if (StrUtil.isBlank(locationAddress)){
            return SaResult.error("当前用户没有分配项目或者仓库地址");
        }
        MPJLambdaWrapper<EquipType>wrapper=new MPJLambdaWrapper<EquipType>()
                .select("count(id)")
//                .eq(PublicTools.checkLoginRole(), Equipment::getLocation, locationAddress)
                ;
        long count = selectJoinOne (Long.class,wrapper);
        return SaResult.data(count);
    }

    @Override
    public SaResult getAllByPageService(Integer current, Integer pageSize) {
        if (current==null){
            current= PAGE_CURRENT;
        }
        if (pageSize==null){
            pageSize=PAGE_SIZE;
        }
        String locationAddress = locationService.getAllByLoginId();
        if (StrUtil.isBlank(locationAddress)) {
            return SaResult.error("当前用户没有分配项目或者仓库地址");
        }
        Page<EquipTypeDto> page=new Page<>(current,pageSize);
        page.setSize(pageSize);
        page.setCurrent(current);
        page.setOptimizeCountSql(false);
        MPJLambdaWrapper<EquipType>wrapper=new MPJLambdaWrapper<EquipType>()
               .selectAll(EquipType.class)
//                类型，不需要根据角色权限查询
//               .eq(PublicTools.checkLoginRole(), Equipment::getLocation, locationAddress)
                ;
        Page<EquipTypeDto> equipTypeDtoPage = selectJoinListPage(page, EquipTypeDto.class, wrapper);
               List<EquipTypeDto> equipTypeDtoList = equipTypeDtoPage.getRecords();
               return SaResult.data(equipTypeDtoList);


    }

    @Override
    public SaResult getByIdService(Integer id) {
        String locationAddress = locationService.getAllByLoginId();
        MPJLambdaWrapper<EquipType>wrapper=new MPJLambdaWrapper<EquipType>()
               .eq(!PublicTools.checkLoginRole(), Equipment::getLocation, locationAddress)
               .eq("id", id);
        EquipTypeDto equipTypeDto = selectJoinOne(EquipTypeDto.class, wrapper);
            if (!BeanUtil.isEmpty(equipTypeDto)){
                return SaResult.data(equipTypeDto);
            }
            else {
                return SaResult.error("未查询到数据");
            }
    }


    @Override
    public SaResult getByNameService(String parentType,Integer current,Integer pageSize) {
        if (current==null){
            current= PAGE_CURRENT;
        }
        if (pageSize==null){
            pageSize=PAGE_SIZE;
        }
        Page<EquipType> page=new Page<>(current,pageSize);

        List<EquipType> equipTypeList = query().like("parent_type", parentType).page(page).getRecords();

        return SaResult.data(BeanUtil.copyToList(equipTypeList, EquipTypeDto.class));
    }

    //    这个
    @Override
    public SaResult getByFullName(String parentType, String childType,Integer current,Integer pageSize) {
        if (current==null){
            current= PAGE_CURRENT;
        }
        if (pageSize==null){
            pageSize=PAGE_SIZE;
        }
        Page<EquipType>page=new Page<>(current,pageSize);

        List<EquipType> equipTypeList = query().like("parent_type", parentType)
                .like("child_type", childType)
                .page(page).getRecords();
        return SaResult.data(BeanUtil.copyToList(equipTypeList, MaterialTypeDto.class));
    }

    @Override
    public SaResult deleteByIdService(Integer id) {
        if (id==null){
            return SaResult.error("id不符合要求！");
        }
        removeById(id);
        return SaResult.ok("succeed!");
    }



    private EquipTypeDto checkedObjStr(EquipTypeDto equipTypeDto){

        String parentType = StrUtil.trim(equipTypeDto.getParentType());
        if (StrUtil.isBlank(parentType)){
            equipTypeDto.setParentType(null);
        }
        else {
            equipTypeDto.setParentType(parentType);
        }

        String childType = StrUtil.trim(equipTypeDto.getChildType());
        if (StrUtil.isBlank(childType)){
            equipTypeDto.setChildType(null);
        }
        else {
            equipTypeDto.setChildType(childType);
        }

        String description = StrUtil.trim(equipTypeDto.getDescription());
        if (StrUtil.isBlank(description)){
            equipTypeDto.setDescription(null);
        }

        return equipTypeDto;
    }


    private List<TypeTree> getEquipTypeTree(List<EquipType> equipTypeList){

        List<EquipTypeDto> equipTypeDtoList = BeanUtil.copyToList(equipTypeList, EquipTypeDto.class);

        Set<String> equipParentStr = new HashSet<>();
        Set<String>equipChildStr=new HashSet<>();

        List<TypeTree> typeTreeList =new ArrayList<>();

//        通过Set集合去重
        for (EquipTypeDto equipTypeDto : equipTypeDtoList) {
            equipParentStr.add(equipTypeDto.getParentType());
            equipChildStr.add(equipTypeDto.getChildType());
        }

        for (String equipParentType : equipParentStr) {
//         1、创建一个equipTreeBso容器
            TypeTree typeTree = new TypeTree();
//         2、容器对象设置一个parentType的属性值为equipType
            typeTree.setValue(equipParentType);
            typeTree.setLabel(equipParentType);
//         3、把容器对象放到equipTreeBsoList集合中； 但现在还存在一个问题，对象中另外一个List字段还是为空，需要
//            把equipTypeList中匹配的childType放到这个List中
            typeTreeList.add(typeTree);
        }

//        遍历equipTreeBsoList
        for (TypeTree typeTree : typeTreeList) {
//            创建一个String类型的List
            List<ChildType>childTypeStr=new ArrayList<>();
//            遍历前端传进来的EquipType
            for (EquipType equipType : equipTypeList) {
                ChildType childType =new ChildType();
//                如果equipType中的ParentType和equipTreeBso中的parentType一致
                if (equipType.getParentType().equals(typeTree.getValue())){
                    childType.setValue(equipType.getChildType());
                    childType.setLabel(equipType.getChildType());
//                    childTypeStr增加一个childType
                    childTypeStr.add(childType);
                }
            }
//            把获取到的childTypeList放到EquipTreeBso中
            typeTree.setChildren(childTypeStr);
        }

        return typeTreeList;
    }

}
